package fm.huanxin.api;

import fm.cache.ConfigCache;
import fm.exception.BizException;
import fm.huanxin.utils.OrgInfo;
import fm.huanxin.utils.TokenUtils;
import io.swagger.client.ApiException;
import io.swagger.client.api.MessagesApi;
import io.swagger.client.model.Msg;
import io.swagger.client.model.MsgContent;
import io.swagger.client.model.UserName;
import org.apache.solr.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by CM on 17/6/4.
 */
public class MessageApi {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageApi.class);

    public static void sendMessage(String message, String toUser, String fromUser) {
        try {
            String accessToken = TokenUtils.getAccessToken();
            MessagesApi api = new MessagesApi();
            Msg msg = new Msg();

            MsgContent msgContent = new MsgContent();
            msgContent.type(MsgContent.TypeEnum.TXT).msg(message);
            UserName userName = new UserName();
            userName.add(toUser);
            Map<String,Object> ext = new HashMap<>();
            ext.put("消息类型",ConfigCache.getConfig("WEB_TITLE")+"系统消息");
            msg.from(fromUser).target(userName).targetType("users").msg(msgContent).ext(ext);
            api.orgNameAppNameMessagesPost(OrgInfo.getOrgName(), OrgInfo.getAppName(), accessToken, msg);
            LOGGER.info("发送消息{}->{}:{}", fromUser, toUser, message);
            System.out.printf("发送消息成功!");
        } catch (Exception e) {
            LOGGER.error("发送消息失败,{}->{}:{}", fromUser, toUser, message, e);
        }
    }


    public static void sendSystemMsg(String msg, String toUser) {
        String systemUser = ConfigCache.getConfig("HUANXIN_SYS_USER");
        if (StringUtils.isEmpty(systemUser)) {
            throw new BizException("环信系统用户账号未配置，消息发送失败!");
        }
        sendMessage(msg, toUser, systemUser);
    }


    public static void sendForumMsg(String msg, String toUser) {
        String forumUser = ConfigCache.getConfig("HUANXIN_FORUM_USER");
        if (StringUtils.isEmpty(forumUser)) {
            throw new BizException("环信社区账号未配置，消息发送失败!");
        }
        sendMessage(msg, toUser, forumUser);
    }
}
